package cn.tedu.vrd07.controller;

import cn.tedu.vrd07.entity.User;
import cn.tedu.vrd07.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/login")
    public int login(User user, String rem, HttpSession session, HttpServletResponse response){
        User u=mapper.check(user.getUsername());
        if (u!=null){
            if (user.getPassword().equals(u.getPassword())){
                //判断是否需要记住用户名和密码
                if (rem!=null){
                    //创建Cookie对象 把需要保存的数据装进去
                    Cookie c1=new Cookie("username", user.getUsername());
                    //设置保存时间 保存一个月
                    c1.setMaxAge(60*60*24*3);
                    Cookie c2=new Cookie("password", user.getPassword());
                    //把Cookie下发给客户端
                    response.addCookie(c1);
                    response.addCookie(c2);
                }

                //把登陆成功的用户对象保存进会话对象
                session.setAttribute("user",u);

                return 1;//登录成功
            }else {
                return 3;//密码错误
            }
        }
        return 2;//用户不存在
    }
    @RequestMapping("/checkLogin")
    public User checkLogin(HttpSession session){
        //把登录成功时保存的用户对象返回给客户端
       return (User) session.getAttribute("user");

    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
